package sn.ugb.cours.jee.zd.tuto;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import sn.ugb.cours.jee.zd.hibernate.dao.Cours;
import sn.ugb.cours.jee.zd.hibernate.sessions.HibernateServlet;
public class HelloWorldServelet extends HibernateServlet {
private static final long serialVersionUID = 3020920976187642993L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
initHibernateSessionFactoryForMe();
sayHelloWorld(request, response);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
sayHelloWorld(req, resp);
}
private void sayHelloWorld(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Date currentDate = new Date();
out.println("Hibernate et Servlet : Hello World !!!");
out.println("<br/>");
printFromDB(out);
out.flush();
out.close();
}
private void printFromDB(PrintWriter out) {
// TODO Auto-generated method stub
ServletContext context = getServletContext();
SessionFactory sessionFactory = getHibernateSessionFactory();
if (sessionFactory.isClosed()) {
sessionFactory.openSession();
}
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
List<Cours> tutos = session.createQuery("from Cours").list();
for (Cours cours : tutos) {
out.println(cours.toString());
out.println("<br/>");
}
session.getTransaction().commit();
}
}